import { _decorator, Component, RigidBody, Collider, v3, MeshRenderer, MeshCollider, CCObject, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('TileItem')
export class TileItem extends Component {
    // 是否自动旋转
    auto_rotation = false;
    static TileItem: any;
    
    // 物体是否被消除的标记
    removed: boolean = false
    // 消除时移动到的目标位置
    removedPos: Vec3 
    // 是否播放消除特效
    playRmovedEff: boolean = false

    // 计算旋转角度的起始时间
    private static starttime = Date.now();
    // 获取基于时间的Y轴旋转角度
    private static getY() {
        let n = Date.now() - this.starttime;
        return n / 10;
    }
    
    // 每帧更新，处理自动旋转
    update() {
        if (this.auto_rotation) {
            this.node.setRotationFromEuler(0, TileItem.getY(), 0);
        }
    }

    // 控制碰撞器的启用状态
    _enableCollider: boolean = false;
    set enableCollider(b) {
        // 保存并重置物体的位置和旋转
        let worldRotation = this.node.children[0].worldRotation.clone();
        this.node.worldPosition = this.node.children[0].worldPosition.clone();
        this.node.children[0].position = v3();
        this.node.children[0].worldRotation = worldRotation;
        // 控制刚体的重力影响
        this.rigidBody.useGravity = b;
    }

    get enableCollider() {
        return this._enableCollider;
    }

    // 销毁物体的碰撞相关组件
    destoryCollider() {
        // 重置位置和旋转
        this.node.children[0].position = v3();
        this.node.children[0].eulerAngles = v3()
        // 销毁所有碰撞器和刚体
        this.collider.map(a => a.destroy())
        this.rigidBody.destroy();
    }

    // 刚体组件引用
    @property
    public rigidBody: RigidBody = null;

    // 添加刚体组件
    addCollider() {
        let _render = this.node.children[0].getComponent(MeshRenderer);
        this.rigidBody = _render.node.addComponent(RigidBody);
        return this.rigidBody;
    }

    // 碰撞器组件数组
    collider: Collider[] = [];
    
    // 组件启动时获取所有碰撞器
    start() {
        this.collider = this.node.children[0].getComponents(Collider);
    }
}
